package cn.com.taiji.learn.sshelloworld.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity(debug = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder())
                .withUser("xtb")
                .password(passwordEncoder().encode("xtb"))
                .roles("USER")
                .and().withUser("ldh")
                .password(passwordEncoder().encode("ldh"))
                .roles("ADMIN");
//        super.configure(auth);
    }

    //单例
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

        @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("error").permitAll()
                .antMatchers("/user/test/bar").permitAll()
                .antMatchers("/user/test/only-user").hasRole("USER")
                .antMatchers("/user/test/foo").hasAnyRole("USER","ADMIN")
                .anyRequest().authenticated();
        http.formLogin().loginPage("/login").permitAll()
                        .loginProcessingUrl("/doLogin");

        http.logout().logoutUrl("/logout").permitAll();
//        super.configure(http);
//            http.csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/images/**","/css/**","/js/**","/favicon.ico");
//        super.configure(web);
    }
}
